// components/upload-image/index.js
const computedBehavior = require('miniprogram-computed').behavior
import { onMultiUploadImage } from '../../http/upload'

Component({
	behaviors: [computedBehavior],

	/**
	 * 组件的属性列表
	 */
	properties: {
		value: { // 值
			type: [String, Array],
			value: []
		},
		limit: { // 上传数量
      type: Number,
      value: 1
		},
		type: { // grid avatar banner
			type: String,
			value: 'grid'
		}
	},

	computed: {
		coverList(data) {
			if (!data.value) return []
			if (typeof data.value === 'string') return [data.value]
      return data.value
		}
	},

	/**
	 * 组件的初始数据
	 */
	data: {

	},

	/**
	 * 组件的方法列表
	 */
	methods: {
		// 预览
		onPreview(event) {
			const { index } = event.currentTarget.dataset
			wx.previewImage({
				urls: this.data.coverList,
				current: this.data.coverList[index]
			})
		},
		// 删除
		onRemove(event) {
			const { index } = event.currentTarget.dataset
			wx.showModal({
				title: '删除提示',
				content: `确定要删除第${index + 1}张图片么？`,
				cancelColor: '#464646',
				confirmColor: '#ff6827',
				success: async res => {
					if (res.confirm) {
						if (Array.isArray(this.properties.value)) {
							this.triggerEvent('finish', {
								url: this.properties.value.filter((v, i) => i !== index)
							})
						} else {
							this.triggerEvent('finish', { url: '' })
						}
					}
				}
			})
		},
		// 上传
		onUpload() {
			onMultiUploadImage({
				maxCount: this.properties.limit,
				curCount: this.data.coverList.length,
				success: (url) => {
					if (Array.isArray(this.properties.value)) {
						this.triggerEvent('finish', {
							url: [...this.properties.value, url]
						})
					} else {
						this.triggerEvent('finish', { url })
					}
				}
			})
		}
	}
})

